package com.kexio.user.controller;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.kexio.auth.annotation.RateLimit;
import com.kexio.auth.dto.MenuInfo;
import com.kexio.auth.dto.UserAuthInfo;
import com.kexio.common.dto.Result;
import com.kexio.user.entity.Tenant;
import com.kexio.user.mapper.TenantMapper;
import com.kexio.user.service.MenuService;
import com.kexio.user.service.PermissionService;
import com.kexio.user.service.RoleService;
import com.kexio.user.service.TenantService;
import com.kexio.user.service.UserService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;

/**
 * 内部服务接口控制器
 * 
 * 提供供框架内部调用的API接口，包括：
 * - 用户认证信息查询
 * - 用户权限查询
 * - 菜单树查询
 * - 数据权限查询
 * - 权限验证服务
 * - 租户信息查询
 * 
 * 注意：这些接口仅供框架内部使用，不对外部业务系统开放
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@RestController
@RequestMapping("/internal")
@Tag(name = "内部服务接口", description = "供框架内部调用的API接口")
public class InternalController {
    
    private static final Logger logger = LoggerFactory.getLogger(InternalController.class);
    
    private final UserService userService;
    private final RoleService roleService;
    private final PermissionService permissionService;
    private final MenuService menuService;
    // 已移除本地缓存层
    private final TenantService tenantService;
    private final TenantMapper tenantMapper;
    @Value("${security.internal.secret:}")
    private String internalSecret;
    @Value("${security.internal.enabled:true}")
    private boolean internalProtectionEnabled;
    
    public InternalController(UserService userService,
                            RoleService roleService,
                            PermissionService permissionService,
                            MenuService menuService,
                            TenantService tenantService,
                            TenantMapper tenantMapper) {
        this.userService = userService;
        this.roleService = roleService;
        this.permissionService = permissionService;
        this.menuService = menuService;
        this.tenantService = tenantService;
        this.tenantMapper = tenantMapper;
    }
    
    private boolean isInternalAuthorized(HttpServletRequest request) {
        if (!internalProtectionEnabled) {
            return true;
        }
        if (internalSecret == null || internalSecret.isEmpty()) {
            // 未配置密钥则拒绝
            return false;
        }
        String header = request.getHeader("X-Internal-Secret");
        return internalSecret.equals(header);
    }
    
    // ==================== 用户认证信息查询 ====================
    
    /**
     * 根据用户名查询用户认证信息
     * 
     * 供JwtAuthenticationFilter使用，获取用户完整认证信息
     */
    @GetMapping("/users/{username}/auth-info")
    @Operation(summary = "查询用户认证信息", description = "根据用户名查询用户认证信息，供框架认证使用")
    public Result<UserAuthInfo> getUserAuthInfo(
            @Parameter(description = "用户名") @PathVariable String username,
            @Parameter(description = "租户ID") @RequestParam String tenantId) {
        
        logger.debug("查询用户认证信息: username={}, tenantId={}", username, tenantId);
        
        UserAuthInfo userAuthInfo = userService.getUserAuthInfo(username);
        
        if (userAuthInfo == null) {
            logger.warn("用户不存在: username={}, tenantId={}", username, tenantId);
            return Result.error("用户不存在");
        }
        
        logger.debug("查询用户认证信息成功: userId={}, permissionCount={}, roleCount={}", 
            userAuthInfo.getUserId(), 
            userAuthInfo.getPermissions() != null ? userAuthInfo.getPermissions().size() : 0,
            userAuthInfo.getRoles() != null ? userAuthInfo.getRoles().size() : 0);
        
        return Result.success("查询成功", userAuthInfo);
    }
    
    /**
     * 根据用户ID查询用户认证信息
     */
    @GetMapping("/users/by-id/{userId}/auth-info")
    @Operation(summary = "根据ID查询用户认证信息", description = "根据用户ID查询用户认证信息")
    public Result<UserAuthInfo> getUserAuthInfoById(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Parameter(description = "租户ID") @RequestParam String tenantId) {
        
        logger.debug("根据ID查询用户认证信息: userId={}, tenantId={}", userId, tenantId);
        
        UserAuthInfo userAuthInfo = userService.getUserAuthInfoById(userId);
        
        if (userAuthInfo == null) {
            logger.warn("用户不存在: userId={}, tenantId={}", userId, tenantId);
            return Result.error("用户不存在");
        }
        
        logger.debug("根据ID查询用户认证信息成功: userId={}, permissionCount={}", 
            userId, userAuthInfo.getPermissions() != null ? userAuthInfo.getPermissions().size() : 0);
        
        return Result.success("查询成功", userAuthInfo);
    }
    
    // ==================== 用户权限查询 ====================
    
    /**
     * 查询用户权限编码列表
     */
    @GetMapping("/users/{userId}/permissions")
    @Operation(summary = "查询用户权限", description = "查询用户拥有的权限编码列表")
    public Result<List<String>> getUserPermissions(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Parameter(description = "租户ID") @RequestParam String tenantId) {
        
        logger.debug("查询用户权限: userId={}, tenantId={}", userId, tenantId);
        
        // 使用UserService查询用户权限代码
        List<String> permissions = userService.getUserPermissions(userId);
        
        logger.debug("查询用户权限成功: userId={}, permissionCount={}", userId, permissions.size());
        
        return Result.success("查询成功", permissions);
    }
    
    /**
     * 检查用户是否拥有指定权限
     */
    @GetMapping("/users/{userId}/permissions/check")
    @Operation(summary = "检查用户权限", description = "检查用户是否拥有指定权限")
    public Result<Boolean> hasPermission(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Parameter(description = "权限编码") @RequestParam String permissionCode,
            @Parameter(description = "租户ID") @RequestParam String tenantId) {
        
        logger.debug("检查用户权限: userId={}, permissionCode={}, tenantId={}", 
            userId, permissionCode, tenantId);
        
        boolean hasPermission = permissionService.hasPermission(userId, permissionCode);
        
        logger.debug("检查用户权限完成: userId={}, permissionCode={}, hasPermission={}", 
            userId, permissionCode, hasPermission);
        
        return Result.success("检查完成", hasPermission);
    }
    
    /**
     * 批量检查用户权限
     */
    @PostMapping("/users/{userId}/permissions/batch-check")
    @RateLimit(count = 60, time = 1)
    @Operation(summary = "批量检查用户权限", description = "批量检查用户是否拥有指定权限列表")
    public Result<Map<String, Boolean>> batchCheckPermissions(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Parameter(description = "租户ID") @RequestParam String tenantId,
            @RequestBody List<String> permissionCodes) {
        
        logger.debug("批量检查用户权限: userId={}, tenantId={}, permissionCount={}", 
            userId, tenantId, permissionCodes.size());
        
        try {
            Map<String, Boolean> results = new java.util.HashMap<>();
            
            // 批量查询用户权限，避免N+1问题
            try {
                // 获取用户所有权限
                List<String> userPermissions = userService.getUserPermissions(userId);
                Set<String> userPermissionSet = new java.util.HashSet<>(userPermissions);
                
                // 批量检查权限
                for (String permissionCode : permissionCodes) {
                    boolean hasPermission = userPermissionSet.contains(permissionCode);
                    results.put(permissionCode, hasPermission);
                }
            } catch (Exception e) {
                // 如果批量查询失败，降级为单个查询
                logger.warn("批量查询用户权限失败，降级为单个查询: userId={}, error={}", userId, e.getMessage());
                for (String permissionCode : permissionCodes) {
                    try {
                        boolean hasPermission = permissionService.hasPermission(userId, permissionCode);
                        results.put(permissionCode, hasPermission);
                    } catch (Exception ex) {
                        logger.warn("检查用户权限失败: userId={}, permissionCode={}, error={}", 
                                   userId, permissionCode, ex.getMessage());
                        results.put(permissionCode, false); // 权限检查失败时默认无权限
                    }
                }
            }
            
            logger.debug("批量检查用户权限完成: userId={}, resultCount={}", userId, results.size());
            
            return Result.success("批量检查完成", results);
            
        } catch (Exception e) {
            logger.error("批量检查用户权限失败: userId={}, tenantId={}, error={}", 
                userId, tenantId, e.getMessage(), e);
            return Result.error("批量检查用户权限失败：" + e.getMessage());
        }
    }
    
    // ==================== 菜单树查询 ====================
    
    /**
     * 查询用户菜单树
     */
    @GetMapping("/users/{userId}/menu-tree")
    @Operation(summary = "查询用户菜单树", description = "查询用户可访问的菜单树结构")
    public Result<List<MenuInfo>> getUserMenuTree(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Parameter(description = "租户ID") @RequestParam String tenantId) {
        
        logger.debug("查询用户菜单树: userId={}, tenantId={}", userId, tenantId);
        
        try {
            // 查询用户菜单树
            List<com.kexio.user.entity.Menu> menus = menuService.getUserMenuTree(userId, tenantId);
            
            // 转换为MenuInfo DTO
            List<MenuInfo> menuInfos = null;
            if (menus != null) {
                menuInfos = menus.stream()
                        .filter(menu -> menu != null)
                        .map(this::convertToMenuInfo)
                        .filter(menuInfo -> menuInfo != null)
                        .collect(Collectors.toList());
            } else {
                menuInfos = new java.util.ArrayList<>();
            }
            
            logger.debug("查询用户菜单树成功: userId={}, menuCount={}", userId, menuInfos.size());
            
            return Result.success("查询成功", menuInfos);
            
        } catch (Exception e) {
            logger.error("查询用户菜单树失败: userId={}, tenantId={}, error={}", 
                userId, tenantId, e.getMessage(), e);
            return Result.error("查询用户菜单树失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询租户所有菜单树
     */
    @GetMapping("/tenants/{tenantId}/menu-tree")
    @Operation(summary = "查询租户菜单树", description = "查询租户的完整菜单树结构")
    public Result<List<MenuInfo>> getTenantMenuTree(
            @Parameter(description = "租户ID") @PathVariable String tenantId) {
        
        logger.debug("查询租户菜单树: tenantId={}", tenantId);
        
        try {
            List<com.kexio.user.entity.Menu> menus = menuService.getMenuTree(tenantId);
            
            // 转换为MenuInfo DTO
            List<MenuInfo> menuInfos = null;
            if (menus != null) {
                menuInfos = menus.stream()
                        .filter(menu -> menu != null)
                        .map(this::convertToMenuInfo)
                        .filter(menuInfo -> menuInfo != null)
                        .collect(Collectors.toList());
            } else {
                menuInfos = new java.util.ArrayList<>();
            }
            
            logger.debug("查询租户菜单树成功: tenantId={}, menuCount={}", tenantId, menuInfos.size());
            
            return Result.success("查询成功", menuInfos);
            
        } catch (Exception e) {
            logger.error("查询租户菜单树失败: tenantId={}, error={}", tenantId, e.getMessage(), e);
            return Result.error("查询租户菜单树失败：" + e.getMessage());
        }
    }
    
    // ==================== 数据权限查询 ====================
    
    /**
     * 查询用户数据权限上下文
     */
    @GetMapping("/users/{userId}/data-scope")
    @Operation(summary = "查询数据权限", description = "JWT架构下数据权限已简化")
    public Result<Object> getUserDataScope(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Parameter(description = "租户ID") @RequestParam String tenantId) {
        
        logger.debug("查询用户数据权限: userId={}, tenantId={}", userId, tenantId);
        
        try {
            // ❌ JWT架构下数据权限上下文已简化
            Object dataScopeContext = userService.getUserDataScope(userId);
            
            // 如果没有查询到数据权限，返回默认权限（简化为Map）
            if (dataScopeContext == null) {
                java.util.Map<String, Object> defaultScope = new java.util.HashMap<>();
                defaultScope.put("userId", userId);
                defaultScope.put("tenantId", tenantId);
                defaultScope.put("scopeType", "SELF"); // 默认仅自己
                dataScopeContext = defaultScope;
                logger.debug("用户无数据权限配置，返回默认SELF权限: userId={}, tenantId={}", userId, tenantId);
            }
            
            logger.debug("查询用户数据权限成功: userId={}, dataScopeContext={}", userId, dataScopeContext);
            
            return Result.success("查询成功", dataScopeContext);
            
        } catch (Exception e) {
            logger.error("查询用户数据权限失败: userId={}, tenantId={}, error={}", 
                userId, tenantId, e.getMessage(), e);
            return Result.error("查询用户数据权限失败：" + e.getMessage());
        }
    }
    
    // ==================== 租户信息查询 ====================
    
    /**
     * 验证租户是否存在且有效
     */
    @GetMapping("/tenants/{tenantId}/validate")
    @Operation(summary = "验证租户", description = "验证租户是否存在且有效")
    public Result<Boolean> validateTenant(
            @Parameter(description = "租户ID") @PathVariable String tenantId) {
        
        logger.debug("验证租户: tenantId={}", tenantId);
        
        try {
            // 验证租户是否存在且有效
            // 实现租户有效性验证逻辑
            // 1. 检查租户ID格式
            if (!tenantId.matches("^[a-zA-Z0-9_-]+$")) {
                logger.warn("租户ID格式无效: {}", tenantId);
                return Result.error("租户ID格式无效");
            }
            
            // 2. 检查租户是否存在（可扩展为查询租户表）
            // 实现租户存在性验证
            boolean tenantExists = validateTenantExists(tenantId);
            if (!tenantExists) {
                logger.warn("租户不存在: {}", tenantId);
                return Result.error("租户不存在");
            }
            
            // 3. 检查租户状态（可扩展）
            // 实现租户状态检查
            boolean tenantActive = validateTenantStatus(tenantId);
            if (!tenantActive) {
                logger.warn("租户状态无效: {}", tenantId);
                return Result.error("租户状态无效");
            }
            
            boolean isValid = tenantExists && tenantActive;
            
            logger.debug("验证租户完成: tenantId={}, isValid={}", tenantId, isValid);
            
            return Result.success("验证完成", isValid);
            
        } catch (Exception e) {
            logger.error("验证租户失败: tenantId={}, error={}", tenantId, e.getMessage(), e);
            return Result.error("验证租户失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询租户基本信息
     */
    @GetMapping("/tenants/{tenantId}/info")
    @Operation(summary = "查询租户信息", description = "查询租户的基本信息")
    public Result<TenantInfo> getTenantInfo(
            @Parameter(description = "租户ID") @PathVariable String tenantId) {
        
        logger.debug("查询租户信息: tenantId={}", tenantId);
        
        try {
            // 从租户服务或数据库查询具体的租户信息
            TenantInfo tenantInfo = buildTenantInfo(tenantId);
            if (tenantInfo == null) {
                logger.warn("无法获取租户信息: {}", tenantId);
                return Result.error("无法获取租户信息");
            }
            
            logger.debug("查询租户信息成功: tenantId={}", tenantId);
            
            return Result.success("查询成功", tenantInfo);
            
        } catch (Exception e) {
            logger.error("查询租户信息失败: tenantId={}, error={}", tenantId, e.getMessage(), e);
            return Result.error("查询租户信息失败：" + e.getMessage());
        }
    }
    
    // ==================== 缓存管理 ====================
    
    /**
     * 刷新用户权限缓存
     */
    @PostMapping("/users/{userId}/refresh-cache")
    @RateLimit(count = 30, time = 1)
    @Operation(summary = "刷新用户缓存", description = "刷新指定用户的权限缓存")
    public Result<Void> refreshUserCache(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Parameter(description = "租户ID") @RequestParam String tenantId,
            HttpServletRequest request) {
        
        logger.debug("刷新用户缓存: userId={}, tenantId={}", userId, tenantId);
        
        try {
            if (!isInternalAuthorized(request)) {
                logger.warn("内部接口鉴权失败: path=/internal/users/{}/refresh-cache", userId);
                return Result.error("内部接口鉴权失败");
            }
            // 触发用户认证信息相关的L1失效由事件侧负责（此处无本地缓存可清）
            
            // 刷新用户权限投影（写穿Redis并递增版本，由监听侧失效L1）
            permissionService.refreshUserPermissionCache(userId);
            
            // 刷新用户菜单相关视图（如有用户维度菜单投影）
            menuService.refreshUserMenuCache(userId, tenantId);
            
            // 角色侧由权限投影刷新时一并处理
            
            logger.debug("刷新用户缓存成功: userId={}, tenantId={}", userId, tenantId);
            
            return Result.<Void>success("缓存刷新成功", null);
            
        } catch (Exception e) {
            logger.error("刷新用户缓存失败: userId={}, tenantId={}, error={}", 
                userId, tenantId, e.getMessage(), e);
            return Result.error("刷新用户缓存失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量刷新权限缓存
     */
    @PostMapping("/tenants/{tenantId}/refresh-cache")
    @RateLimit(count = 10, time = 1)
    @Operation(summary = "刷新租户缓存", description = "刷新指定租户的权限缓存")
    public Result<Void> refreshTenantCache(
            @Parameter(description = "租户ID") @PathVariable String tenantId,
            HttpServletRequest request) {
        
        logger.debug("刷新租户缓存: tenantId={}", tenantId);
        
        try {
            if (!isInternalAuthorized(request)) {
                logger.warn("内部接口鉴权失败: path=/internal/tenants/{}/refresh-cache", tenantId);
                return Result.error("内部接口鉴权失败");
            }
            permissionService.refreshPermissionCache();
            menuService.refreshMenuCache();
            
            logger.debug("刷新租户缓存成功: tenantId={}", tenantId);
            
            return Result.<Void>success("租户缓存刷新成功", null);
            
        } catch (Exception e) {
            logger.error("刷新租户缓存失败: tenantId={}, error={}", tenantId, e.getMessage(), e);
            return Result.error("刷新租户缓存失败：" + e.getMessage());
        }
    }
    
    // ==================== 辅助方法 ====================
    
    /**
     * 转换Menu实体为MenuInfo DTO
     * 
     * @param menu Menu实体
     * @return MenuInfo DTO
     */
    private MenuInfo convertToMenuInfo(com.kexio.user.entity.Menu menu) {
        if (menu == null) {
            return null;
        }
        
        MenuInfo menuInfo = new MenuInfo();
        menuInfo.setId(menu.getId());
        menuInfo.setParentId(menu.getParentId());
        menuInfo.setName(menu.getName());
        menuInfo.setTitle(menu.getTitle());
        menuInfo.setPath(menu.getPath());
        menuInfo.setComponent(menu.getComponent());
        menuInfo.setIcon(menu.getIcon());
        menuInfo.setMenuType(menu.getMenuType());
        menuInfo.setPermission(menu.getPermission());
        menuInfo.setOrderNo(menu.getOrderNo());
        menuInfo.setVisible(menu.getVisible());
        menuInfo.setStatus(menu.getStatus());
        
        // 设置菜单元数据
        MenuInfo.MenuMeta meta = new MenuInfo.MenuMeta();
        meta.setTitle(menu.getTitle());
        meta.setIcon(menu.getIcon());
        meta.setKeepAlive(menu.getIsCache());
        meta.setRequiresAuth(true); // 默认需要认证
        meta.setHideInMenu(!Boolean.TRUE.equals(menu.getVisible()));
        
        // 设置外链信息
        if (Boolean.TRUE.equals(menu.getIsFrame())) {
            meta.setTarget("_blank");
        }
        
        menuInfo.setMeta(meta);
        
        // 递归转换子菜单
        if (menu.getChildren() != null && !menu.getChildren().isEmpty()) {
            List<MenuInfo> children = menu.getChildren().stream()
                    .filter(childMenu -> childMenu != null) // 过滤空子菜单
                    .map(this::convertToMenuInfo)
                    .filter(childMenuInfo -> childMenuInfo != null) // 过滤转换失败的子菜单
                    .collect(Collectors.toList());
            
            if (!children.isEmpty()) {
                menuInfo.setChildren(children);
            }
        }
        
        return menuInfo;
    }
    
    // ==================== 私有方法 ====================
    
    /**
     * 验证租户是否存在
     */
    private boolean validateTenantExists(String tenantId) {
        try {
            // 1. 基础参数验证
            if (!org.springframework.util.StringUtils.hasText(tenantId)) {
                logger.debug("租户ID为空");
                return false;
            }
            
            // 2. 租户ID格式验证
            if (!isValidTenantIdFormat(tenantId)) {
                logger.debug("租户ID格式无效: {}", tenantId);
                return false;
            }
            
            // 3. 查询租户存在性
            // 已实现：通过TenantService查询sys_tenant表
            // 当前生产级实现：模拟数据库查询
            boolean exists = queryTenantFromDatabase(tenantId);
            
            logger.debug("租户存在性验证: tenantId={}, exists={}", tenantId, exists);
            return exists;
            
        } catch (Exception e) {
            logger.error("验证租户存在性失败: tenantId={}, error={}", tenantId, e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 验证租户状态是否有效
     */
    private boolean validateTenantStatus(String tenantId) {
        try {
            // 1. 先验证租户是否存在
            if (!validateTenantExists(tenantId)) {
                return false;
            }
            
            // 2. 查询租户状态
            // 已实现：通过TenantService查询租户状态
            TenantStatus status = queryTenantStatus(tenantId);
            
            // 3. 验证状态是否有效
            boolean isValid = isValidTenantStatus(status);
            
            logger.debug("租户状态验证: tenantId={}, status={}, isValid={}", tenantId, status, isValid);
            return isValid;
            
        } catch (Exception e) {
            logger.error("验证租户状态失败: tenantId={}, error={}", tenantId, e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 构建租户信息
     */
    private TenantInfo buildTenantInfo(String tenantId) {
        try {
            if (!org.springframework.util.StringUtils.hasText(tenantId)) {
                logger.warn("构建租户信息失败：租户ID为空");
                return null;
            }
            
            // 实际项目中应该执行：SELECT * FROM sys_tenant WHERE tenant_id = ? AND deleted = 0
            // 当前生产级实现：模拟完整的租户信息查询
            TenantInfo tenantInfo = queryFullTenantInfo(tenantId);
            
            if (tenantInfo == null) {
                logger.warn("租户信息不存在: tenantId={}", tenantId);
                return null;
            }
            
            // 填充计算字段
            enrichTenantInfo(tenantInfo);
            
            logger.debug("构建租户信息成功: tenantId={}, tenantName={}", 
                        tenantInfo.getTenantId(), tenantInfo.getTenantName());
            
            return tenantInfo;
            
        } catch (Exception e) {
            logger.error("构建租户信息失败: tenantId={}, error={}", tenantId, e.getMessage(), e);
            return null;
        }
    }
    
    // ==================== 租户管理私有方法 ====================
    
    /**
     * 验证租户ID格式
     */
    private boolean isValidTenantIdFormat(String tenantId) {
        if (tenantId == null || tenantId.trim().isEmpty()) {
            return false;
        }
        
        // 租户ID规则：2-32位字符，只能包含字母、数字、下划线、连字符
        String pattern = "^[a-zA-Z0-9_-]{2,32}$";
        return tenantId.matches(pattern);
    }
    
    /**
     * 从数据库查询租户存在性
     */
    private boolean queryTenantFromDatabase(String tenantId) {
        try {
            // 真正的数据库查询：SELECT COUNT(*) FROM sys_tenant WHERE tenant_id = ? AND deleted = 0
            int count = tenantMapper.countByTenantId(tenantId);
            boolean exists = count > 0;
            
            logger.debug("数据库查询租户存在性: tenantId={}, exists={}", tenantId, exists);
            return exists;
            
        } catch (Exception e) {
            logger.error("查询租户存在性失败: tenantId={}, error={}", tenantId, e.getMessage());
            return false;
        }
    }
    
    /**
     * 查询租户状态
     */
    private TenantStatus queryTenantStatus(String tenantId) {
        try {
            // 使用真实的TenantService查询租户状态
            Integer status = tenantService.getTenantStatus(tenantId);
            
            if (status == null) {
                return TenantStatus.UNKNOWN;
            }
            
            // 根据数据库状态值转换为枚举
            switch (status) {
                case 0:
                    return TenantStatus.DISABLED;
                case 1:
                    return TenantStatus.ACTIVE;
                case 2:
                    return TenantStatus.TRIAL;
                case 3:
                    return TenantStatus.EXPIRED;
                case 4:
                    return TenantStatus.PENDING;
                default:
                    return TenantStatus.UNKNOWN;
            }
            
        } catch (Exception e) {
            logger.error("查询租户状态失败: tenantId={}, error={}", tenantId, e.getMessage());
            return TenantStatus.UNKNOWN;
        }
    }
    
    /**
     * 验证租户状态是否有效
     */
    private boolean isValidTenantStatus(TenantStatus status) {
        return status == TenantStatus.ACTIVE || status == TenantStatus.TRIAL;
    }
    
    /**
     * 查询完整的租户信息
     */
    private TenantInfo queryFullTenantInfo(String tenantId) {
        try {
            // 使用真实的TenantService查询租户信息
            Tenant tenant = tenantService.getTenantByTenantId(tenantId);
            
            if (tenant == null) {
                return null;
            }
            
            // 将数据库实体转换为内部DTO
            TenantInfo tenantInfo = new TenantInfo();
            tenantInfo.setTenantId(tenant.getTenantId());
            tenantInfo.setTenantName(tenant.getTenantName());
            tenantInfo.setTenantType(tenant.getTenantType());
            // 使用真实的状态转换方法
            tenantInfo.setStatus(convertStatusToString(tenant.getStatus()));
            tenantInfo.setMaxUsers(tenant.getMaxUsers());
            tenantInfo.setCreateTime(tenant.getCreateTime());
            tenantInfo.setExpireTime(tenant.getExpireTime());
            
            // 查询当前用户数量
            int currentUsers = getCurrentUserCount(tenantId);
            tenantInfo.setCurrentUsers(currentUsers);
            
            return tenantInfo;
            
        } catch (Exception e) {
            logger.error("查询完整租户信息失败: tenantId={}, error={}", tenantId, e.getMessage());
            return null;
        }
    }
    
    /**
     * 丰富租户信息
     */
    private void enrichTenantInfo(TenantInfo tenantInfo) {
        if (tenantInfo == null) {
            return;
        }
        
        try {
            // 计算剩余天数
            if (tenantInfo.getExpireTime() != null) {
                long daysLeft = java.time.Duration.between(
                    java.time.LocalDateTime.now(), 
                    tenantInfo.getExpireTime()
                ).toDays();
                tenantInfo.setDaysLeft((int) Math.max(0, daysLeft));
            }
            
            // 计算使用率
            if (tenantInfo.getMaxUsers() > 0) {
                double usageRate = (double) tenantInfo.getCurrentUsers() / tenantInfo.getMaxUsers() * 100;
                tenantInfo.setUsageRate(Math.round(usageRate * 100.0) / 100.0);
            }
            
            logger.debug("租户信息丰富完成: tenantId={}, daysLeft={}, usageRate={}%", 
                        tenantInfo.getTenantId(), tenantInfo.getDaysLeft(), tenantInfo.getUsageRate());
            
        } catch (Exception e) {
            logger.warn("丰富租户信息失败: tenantId={}, error={}", 
                       tenantInfo.getTenantId(), e.getMessage());
        }
    }
    
    /**
     * 生成租户名称
     */
    private String generateTenantName(String tenantId) {
        // 生产级实现：根据租户ID生成有意义的名称
        if ("default".equals(tenantId)) {
            return "默认租户";
        } else if (tenantId.startsWith("enterprise")) {
            return "企业租户-" + tenantId.substring(10);
        } else if (tenantId.startsWith("trial")) {
            return "试用租户-" + tenantId.substring(5);
        } else {
            return "租户-" + tenantId;
        }
    }
    
    /**
     * 确定租户类型
     */
    private String determineTenantType(String tenantId) {
        if (tenantId.contains("enterprise")) {
            return "ENTERPRISE";
        } else if (tenantId.contains("trial") || tenantId.contains("demo")) {
            return "TRIAL";
        } else if (tenantId.contains("personal")) {
            return "PERSONAL";
        } else {
            return "STANDARD";
        }
    }
    
    /**
     * 确定最大用户数
     */
    private int determinateMaxUsers(String tenantId) {
        String type = determineTenantType(tenantId);
        switch (type) {
            case "ENTERPRISE":
                return 1000;
            case "STANDARD":
                return 100;
            case "TRIAL":
                return 10;
            case "PERSONAL":
                return 5;
            default:
                return 50;
        }
    }
    
    /**
     * 获取当前用户数量
     */
    private int getCurrentUserCount(String tenantId) {
        try {
            // 使用真实的TenantService查询用户数量
            return tenantService.getUserCountByTenantId(tenantId);
        } catch (Exception e) {
            logger.error("查询租户用户数量失败: tenantId={}, error={}", tenantId, e.getMessage());
            return 0; // 出错时返回0
        }
    }
    
    /**
     * 租户状态枚举
     */
    private enum TenantStatus {
        ACTIVE("正常"),
        DISABLED("禁用"),
        EXPIRED("过期"),
        PENDING("待激活"),
        TRIAL("试用"),
        UNKNOWN("未知");
        
        private final String description;
        
        TenantStatus(String description) {
            this.description = description;
        }
        
        public String getDescription() {
            return description;
        }
    }
    
    /**
     * 状态值转换为字符串
     */
    private String convertStatusToString(Integer status) {
        if (status == null) {
            return "未知";
        }
        
        switch (status) {
            case 0:
                return "禁用";
            case 1:
                return "正常";
            case 2:
                return "试用";
            case 3:
                return "过期";
            case 4:
                return "待审核";
            default:
                return "未知";
        }
    }
    
    /**
     * 租户信息类
     */
    private static class TenantInfo {
        private String tenantId;
        private String tenantName;
        private String tenantType;
        private String status;
        private java.time.LocalDateTime createTime;
        private java.time.LocalDateTime expireTime;
        private int maxUsers;
        private int currentUsers;
        private int daysLeft;
        private double usageRate;
        
        // Getters and setters
        public String getTenantId() { return tenantId; }
        public void setTenantId(String tenantId) { this.tenantId = tenantId; }
        
        public String getTenantName() { return tenantName; }
        public void setTenantName(String tenantName) { this.tenantName = tenantName; }
        
        public String getTenantType() { return tenantType; }
        public void setTenantType(String tenantType) { this.tenantType = tenantType; }
        
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        
        public java.time.LocalDateTime getCreateTime() { return createTime; }
        public void setCreateTime(java.time.LocalDateTime createTime) { this.createTime = createTime; }
        
        public java.time.LocalDateTime getExpireTime() { return expireTime; }
        public void setExpireTime(java.time.LocalDateTime expireTime) { this.expireTime = expireTime; }
        
        public int getMaxUsers() { return maxUsers; }
        public void setMaxUsers(int maxUsers) { this.maxUsers = maxUsers; }
        
        public int getCurrentUsers() { return currentUsers; }
        public void setCurrentUsers(int currentUsers) { this.currentUsers = currentUsers; }
        
        public int getDaysLeft() { return daysLeft; }
        public void setDaysLeft(int daysLeft) { this.daysLeft = daysLeft; }
        
        public double getUsageRate() { return usageRate; }
        public void setUsageRate(double usageRate) { this.usageRate = usageRate; }
    }
}
